/**
 * 
 */
package com.bolbachchan.blog.controller.posts;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bolbachchan.blog.controller.common.DefaultController;
import com.bolbachchan.blog.form.posts.UpdatePostForm;
import com.bolbachchan.blog.hibernate.domain.Posts;
import com.bolbachchan.blog.service.posts.UserPostsService;
import com.bolbachchan.common.ui.Output;
import com.bolbachchan.common.ui.ScreenMessage.ScreenMessageType;

/**
 * @author Chaitanya
 * 
 */
@Controller
@RequestMapping(value = "pages/updatePost")
public class UpdatePostController extends DefaultController<UpdatePostForm> {

    private final static String POST_ID = "postId";

    @Autowired
    private UserPostsService userPostsService;

    @RequestMapping(method = RequestMethod.GET)
    public String get(@RequestParam(POST_ID) int postId, @ModelAttribute(FBB) UpdatePostForm fbb, Model model) {
	if (postId == 0) {
	    return ERROR_PAGE_VIEW;
	}
	Posts post = userPostsService.getPostsByPostId(postId);
	fbb.setPost(post);
	model.addAttribute(FBB, fbb);

	return UPDATE_POST_VIEW;
    }

    @Override
    public @ResponseBody
    Output post(@ModelAttribute(FBB) UpdatePostForm fbb, BindingResult result) {
	try {
	    userPostsService.updatePost(fbb.getPost());
	}
	catch (Exception e) {
	    return messageUtils.getNewDefaultOutputWithMessage(ScreenMessageType.ERROR, UPDATE_POST_FAILURE_MESSAGE);
	}
	return messageUtils.getNewDefaultOutputWithMessage(ScreenMessageType.SUCCESS, UPDATE_POST_SUCCESS_MESSAGE);
    }
}
